package list_;

import java.util.*;

/**
 * @Author 小闽
 * @Date 2024/10/26 23:22
 * @PackageName: list_
 * @ClassName: ListExercise01_
 * @Description: list练习1
 * @Version 1.0
 */
@SuppressWarnings({"all"})
public class ListExercise01_ {
    public static void main(String[] args) {
        /**
         * 使用List的实现添加三本图书，并遍历，打印如下效果
         * 名称：xx       价格： xx       作者：xx
         * 名称：xx       价格： xx       作者：xx
         * 名称：xx       价格： xx       作者：xx
         *
         * 要求：
         *  1）按价格排序，从低到高（使用冒泡法）
         *  2）要求使用ArrayList、LinkedList和Vector三种集合实现
         */
        List list = new ArrayList();
        List linkedList = new LinkedList();
        List vector = new Vector();
        Book book1 = new Book("红楼梦",100,"曹雪芹");
        Book book2 = new Book("西游记",200,"吴承恩");
        Book book3 = new Book("三国志",300,"罗贯中");
        Book book4 = new Book("水浒传",10,"施耐庵");
        list.add(book1);
        list.add(book2);
        list.add(book3);
        list.add(book4);
        System.out.println("===这是输出前的排序===");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }
        bubbleSort(list);
        System.out.println("===这是输出后的排序===");
        for (Object object : list) {
            System.out.println(object);
        }

    }
    /**
     * 冒泡排序
     * 从小到大
     */
    public static void bubbleSort(List list){
        for (int i = 0; i < list.size() -1; i++){
            for (int j = 0; j < list.size() -1 -i; j++){
                // 获取Book对象
                Book book = (Book) list.get(j); // 因为Book保存到list中是一个对象类型，所以需要进行向下转型
                Book book1 = (Book) list.get(j+1); // 同样
                if (book.getPrice() > book1.getPrice()){
                    list.set(j, book1);
                    list.set(j+1, book);
                }
            }
        }
    }
}
class Book{
    private String name;
    private double price;
    private String author;

    public Book(String name, double price, String author) {
        this.name = name;
        this.price = price;
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return name + "\t\t" + price + "\t\t" + author;
    }
}
